package common

import (
	"github.com/minio/minio-go"
	"github.com/spf13/viper"
	"log"
	"mime/multipart"
	"net/http"
	"path"
	"strconv"
	"time"
)

var bucketName string

/**
 * 获得minio连接对象
 */
func MinioClient() (*minio.Client, error) {
	endpoint := viper.GetString("minio.endpoint")
	accessKey := viper.GetString("minio.accessKey")
	secretKey := viper.GetString("minio.secretKey")
	useSSL := viper.GetBool("minio.useSSL")
	bucketName = viper.GetString("minio.bucketName")
	client, err := minio.New(endpoint, accessKey, secretKey, useSSL)
	if err != nil {
		log.Println("minio连接异常: ", err)
		return nil, err
	}
	// 获得连接对象初始化桶
	bucketErr := CreateBucket(client, bucketName, "")
	if bucketErr != nil {
		return nil, bucketErr
	}
	return client, nil
}

// 创建文件存储在哪个位置的桶 时区
func CreateBucket(client *minio.Client, bucketName string, location string) error {
	err := client.MakeBucket(bucketName, location)
	// 如果创建失败
	if err != nil {
		exists, err := client.BucketExists(bucketName)
		if err != nil {
			log.Fatalln("桶创建失败:", err)
			return err
		}
		if exists {
			return nil
		}
	}
	log.Println("桶创建成功：", bucketName)
	return nil
}

// 文件上传方法
func Upload(file *multipart.FileHeader) (string, error) {
	client, err := MinioClient()
	if err != nil {
		log.Fatalln("上传连接对象异常：", err)
		return "上传连接对象异常", err
	}
	open, err1 := file.Open()
	if err1 != nil {
		log.Fatalln("文件打开异常：", err1)
		return "文件打开异常", err1
	}
	defer open.Close()
	// 获得文件名  /bucket/times+filesufix
	objectName := "/" + strconv.FormatInt(time.Now().UnixNano(), 10) + path.Ext(file.Filename)
	// 获取文件类型
	buf := make([]byte, 512)
	_, readErr := open.Read(buf)
	if readErr != nil {
		return "文件类型读取异常", readErr
	}
	_, e := client.PutObject(bucketName, objectName, open, file.Size, minio.PutObjectOptions{ContentType: http.DetectContentType(buf)})
	if e != nil {
		log.Fatalln("文件上传失败：", e)
		return "文件上传失败", e
	}
	return "/" + bucketName + objectName, nil
}
